<?php
/**
 *  Panorama-Picture Plugin
 *
 *  @license    GPL 2 ( http://www.gnu.org/licenses/gpl.html )
 *  @author     jaloma.ac [at] googlemail [dot] com
 *
 *  Description:
 *  Plugin to display Panorama-Pictures with Java-Applet http://www.tshsoft.de/panostudioapplet/index.html
 *
 *  Acknowledgements:
 *  The java applet author(s)
 */

if (!defined('DOKU_INC'))define('DOKU_INC', realpath(dirname( __FILE__ ).'/../../').'/');
if (!defined('DOKU_PLUGIN'))define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
require_once (DOKU_PLUGIN.'syntax.php');
require_once (DOKU_PLUGIN.'panorama/render_helper.php');

class syntax_plugin_panorama_panorama2 extends DokuWiki_Syntax_Plugin
{
    var $dflt = array (
    'width'=>800,
    'height'=>400,
    'name'=>'',
    'file'=>'',
    'hsfile'=>'off',
    'mode'=>'java'
    );
    /**
     *  Plugin Info
     */
    function getInfo()
    {
        return array (
        'author'=>'Jürgen A. Lamers',
        'email'=>'jaloma.ac [at] googlemail [dot] com',
        'date'=>@file_get_contents(DOKU_PLUGIN . 'panorama/VERSION'),
        'name'=>'panorama2',
        'desc'=>'Panorama-Picture Plugin <panorama2 name="" width="" height="" mode="" file="" hsfile="">xmlData</panorama2>',
        'url'=>'http://www.dokuwiki.org/plugin:panorama',
        );
    }

    /**
     *  Typology?
     */
    function getType()
    {
        return 'substition';
    }

    /**
     *  Sort Code?
     */
    function getSort()
    {
        return 316;
    }

    /**
     *  Pattern Matching?
     */
    function connectTo($mode)
    {
        $this->Lexer->addSpecialPattern('<panorama2 ?[^>\n]*>.*?</panorama2>', $mode, 'plugin_panorama_panorama2');
    }

    function matchLength()
    {
        return strlen("<panorama2");
    }
    /**
     *  Parsing
     *  1. Very rough parsing involved
     *  2. Applet parameters not included
     */
    function handle($match, $state, $pos, & $handler)
    {
        list ($str_params, $str_images) = explode('>', substr($match, $this->matchLength(), -1*$this->matchLength()-2), 2);
        $thumb = $this->_extract_params($str_params);
        $imgs = $this->_extract_images($str_images);
        return array ($thumb, $imgs);

    }
    /**
     * extract parameters for the googlemap from the parameter string
     *
     * @param   string    $str_params   string of key="value" pairs
     * @return  array                   associative array of parameters key=>value
     */
    function _extract_params($str_params)
    {
        $param = array ();
        preg_match_all('/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER);
        if (sizeof($param) == 0)
        {
            preg_match_all("/(\w*)='(.*?)'/us", $str_params, $param, PREG_SET_ORDER);
        }
        // parse match for instructions, break into key value pairs
        $gmap = $this->dflt;
        foreach ($param as $kvpair)
        {
            list ($match, $key, $val) = $kvpair;
            if ( isset ($gmap[$key]))$gmap[$key] = $val;
        }

        return $gmap;
    }
    function _extract_images($str_images)
    {
        return $str_images;
    }

    /**
     *  Rendering
     */
    function render($mode, & $renderer, $all_data)
    {
        if ($mode == 'xhtml')
        {
            global $conf;
            $data = $all_data[0];
            $name = $data['name'];
            $file = $data['file'];
            $file = $this->createFileName4Picture($file);
            if (strpos($file, "http://") === null)
            {
                $fqPicFile = getcwd().$file;
                if (!file_exists($fqPicFile))
                {
                    $renderer->doc .= " File not found ".$fqPicFile;
                    return true;
                }
            }
            $hsfile = $data['hsfile'];
            if ($hfile != 'off')
            {
                $hsfile = $this->createFileName4Picture($hsfile);
                if (strpos($hsfile, "http://") === null)
                {
                    $fqHSPicFile = getcwd().$hsfile;
                    if (!file_exists($fqHSPicFile))
                    {
                        $renderer->doc .= " Hotspot-File not found ".$fqHSPicFile;
                        return true;
                    }
                }
            }

            $xmlFileName = str_replace(':', '/', $name);
            $xmlData = $all_data[1];
            $this->writeXMLFile($xmlFileName, $file, $xmlData, $hsfile);
            $mode = $data['mode'];
            $txt = "";
            if ($mode == null || $mode == 'java')
            {
                $txt = render_helper::_render_java($data);
            } elseif ($mode == 'swf' || $mode == 'flash')
            {
                $txt = render_helper::_render_swf($data);
            }
            if ($this->getConf('showPanoramaUrl'))
            {
                $txt .= '
<br/>
Powered by <a href="http://www.tshsoft.com/panostudioapplet/index.html">PanoramaStudio Viewer</a>';
            }
            $renderer->doc .= $txt;
            return true;
        } else
        {
            return false;
        }
    }

    function createFileName4Picture($file)
    {
        global $conf;
        if (strpos($file, "http://") === false)
        {
            if (strpos($file, ':') !== false)
            {
                $dataDir = $conf['savedir'].'/media';
                $file = str_replace(':', '/', $file);
                $file = $dataDir.'/'.$file;
            }
        }
        return $file;
    }
    function writeXMLFile($xmlFileName, $picFileName, $panoInfo, $hotspotFile)
    {
        global $conf;
        $dataDir = $conf['savedir'].'/media';
        if ($dataDir[0] == '.')
        {
            $dataDir = substr($dataDir, 1);
        }
        if ($picFileName[0] == '.')
        {
            $picFileName = substr($picFileName, 1);
        }
        $currentPath = getcwd();
        $fqFileName = $currentPath.$dataDir.'/'.$xmlFileName.'.xml';
        if (strpos($currentPath, '\\') !== false)
        {
            $fqFileName = str_replace('/', '\\', $fqFileName);
        }
        $panoInfo = str_replace('[', '<', $panoInfo);
        $panoInfo = str_replace(']', '>', $panoInfo);
        $picFileName = '<file>'.$picFileName.'</file>';
        if ($hotspotFile != 'off' && $hotspotFile != '')
        {
            $picFileName .= "\n".'<hsfile>'.$hotspotFile.'</hsfile>';
        }
        $fstream = fopen($fqFileName, 'w');
        $head = '<?xml version="1.0" encoding="ISO-8859-1" 
?>
<panoramaStudioViewer>
    <panorama>
        ';
        $foot = '
    </panorama>
</panoramaStudioViewer>';
fwrite($fstream, $head);
fwrite($fstream, $picFileName);
fwrite($fstream,$panoInfo);
fwrite($fstream, $foot);
fclose($fstream);
}
} // clas
